import 'package:flutter/material.dart';
import 'package:open_source_china/api/user.dart';
import 'package:open_source_china/model/user.dart';
import 'package:open_source_china/pages/DiscoveryPage/DiscoveryPage.dart';
import 'package:open_source_china/pages/DynamicPage/DynamicPage.dart';
import 'package:open_source_china/pages/MinePage/MinePage.dart';
import 'package:open_source_china/pages/NewsListPage/NewsListPage.dart';
import 'package:open_source_china/widget/MyDrawer.dart';
import 'package:open_source_china/widget/NavigationBarItemView.dart';

class HomePage extends StatefulWidget {
  final String title;
  HomePage({this.title});
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  List<String> appBarTitle = ["资讯", "动态", "发现", "我的"];
  List<NavigationBarItemView> navigationIconViews;
  int currentIndex = 0;
  List<Widget> pages = [];
  PageController controller;
  User user;

  @override
  void initState() {
    super.initState();
    navigationIconViews = [
      NavigationBarItemView(iconData: 0xe61b, title: "资讯", color: Colors.grey),
      NavigationBarItemView(iconData: 0xe629, title: "动态", color: Colors.grey),
      NavigationBarItemView(iconData: 0xe6c8, title: "发现", color: Colors.grey),
      NavigationBarItemView(iconData: 0xe605, title: "我的", color: Colors.grey),
    ];
    pages = [NewsList(), DynamicPage(), DiscoveryPage(), MinePage()];
    controller = PageController(initialPage: currentIndex);
    showUserInfo();
  }

  showUserInfo() async {
    if (mounted) {
      UserApi.getInfo().then((user) {
        setState(() {
          this.user = user;
        });
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(appBarTitle[currentIndex]),
      ),
      body: PageView.builder(
        physics: NeverScrollableScrollPhysics(), // 禁止PageView滑动
        itemCount: pages.length,
        controller: controller,
        itemBuilder: (context, index) => pages[index],
        onPageChanged: (index) => this.setState(() {
          currentIndex = index;
        }),
      ),
      drawer: MyDrawer(
        name: user?.name ?? "person",
        avatarPath: user?.avatar ?? "lib/assets/images/avatar.png",
        menuTitles: ["发布动态", "动态黑屋", "关于", "设置"],
        menuIcons: [Icons.send, Icons.home, Icons.error, Icons.settings],
      ),
      bottomNavigationBar: BottomNavigationBar(
          type: BottomNavigationBarType.fixed,
          onTap: (index) => this.setState(() {
                currentIndex = index;
                controller.jumpToPage(index);
              }),
          currentIndex: currentIndex,
          items: navigationIconViews.map((e) => e.item).toList()),
    );
  }
}
